package com.weaponlin.domain;

import java.util.zip.CRC32;

public class GetTable {

    public static void main(String[] args) {
        String tableName = getRecordPosition("cashpay_order", "t_common_order", "4190393",
                100, 1000);
        System.out.println(tableName);

    }
    // `F_trade_status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '订单状态,1为等待付款,2为付款成功,3为交易关闭,4为交易取消',
    // template: select count(1) from ? where F_partner_id='?' and F_trade_status=2;
    // select count(1) from cashpay_order_30.t_partner_order_830 where F_partner_id='100002830' and F_trade_status=2;

    public static String getRecordPosition(String database, String table, String userId, int databaseNum, int tableNum) {
        long crc = getCRC32(userId);
        return getRecordPostion(database, table, crc, databaseNum, tableNum);
    }

    public static String getRecordPostion(String database, String table, long crc, int databaseNum, int tableNum) {
        String databaseIndex = getRecordIndex(crc, databaseNum);
        String tableIndex = getRecordIndex(crc, tableNum);
        StringBuilder sb = new StringBuilder();
        sb.append(database).append("_").append(databaseIndex).append(".");
        sb.append(table).append("_").append(tableIndex);
        return sb.toString();
    }

    public static long getCRC32(String userId) {
        CRC32 crc32 = new CRC32();
        crc32.update(userId.getBytes());
        return crc32.getValue();
    }








    public static String getPartnerPartion(String database, String table, String partnerId, int databaseNum, int tableNum) {
        long crc = Long.valueOf(partnerId);
        String databaseIndex = getRecordIndex(crc, databaseNum);
        String tableIndex = getRecordIndex(crc, tableNum);
        StringBuilder sb = new StringBuilder();
        sb.append(database).append("_").append(databaseIndex).append(".");
        sb.append(table).append("_").append(tableIndex);
        return sb.toString();
    }

    private static String getRecordIndex(long shardId, int count) {
        if (count < 10) {
            return String.valueOf(shardId % 10);
        }
        return String.format("%0" + (getDigitNum(count) - 1) + "d", shardId % count);
    }

    public static int getDigitNum(int tableCount) {
        if (tableCount == 0) {
            return 1;
        }
        int result = 0;
        while (tableCount != 0) {
            result++;
            tableCount /= 10;
        }
        return result;
    }
}
